﻿using System;
using System.IO;

// SkypeScreenSaver, Copyright Mirosław M. Mączka.  All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

namespace SL
{
    class Log
    {
        public static string LogName {get;private set;}
        private static bool isCantOpen = false;
        private static StreamWriter sw = null;
        //
        [System.Diagnostics.Conditional("DEBUG")]
        public static void Write(string fmt, params object[] args)
        {
            if(isCantOpen)return;
            //
            if (null == sw)
            {
                if (!openLog()) return;
            }
            //
            writeLog(false, fmt, args);
            //
            return;
        }
        [System.Diagnostics.Conditional("DEBUG")]
        public static void FWrite(string fmt, params object[] args)
        {
            if (isCantOpen) return;
            //
            if (null == sw)
            {
                if (!openLog()) return;
            }
            //
            writeLog(true, fmt, args);
            //
            return;
        }




        private static bool openLog()
        {
            try
            {
                //
                string ln = "SLog_" + System.Reflection.Assembly.GetEntryAssembly().GetName().Name.Replace(' ', '_') + ".txt";
                LogName = Path.Combine(@"\Temp", ln);
                sw = File.AppendText(LogName);
            }
            catch
            {
                sw = null;
                isCantOpen = true;
                return false;
            }
            return true;
        }
        private static bool writeLog(bool withFunctionName, string fmt, params object[] args)
        {
            if (null == sw) return false;
            //
            DateTime dt = DateTime.Now;
            string s;
            try
            {
                string ss = string.Format(fmt, args);
                if (withFunctionName)
                {
                    s = string.Format("{0:#0}:{1:00}.{2:00} => {3}() [{4}]", dt.Hour, dt.Minute, dt.Second, new System.Diagnostics.StackFrame(2, true).GetMethod().Name, ss);
                }
                else
                {
                    s = string.Format("{0:#0}:{1:00}.{2:00} => [{3}]", dt.Hour, dt.Minute, dt.Second, ss);
                }
                //
                sw.WriteLine(s); sw.Flush();
            }
            catch
            {
                return false;
            }
            //
            return true;
        }
    }//class
}//namespace
